package admin_menu_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/ctype"
	"blog_go/models/res"
	"github.com/fatih/structs"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type MenuUpdateReq struct {
	ID           uint        `json:"id" structs:"-"` // structs不写的话转成ID,-表示不转map
	Title        string      `json:"title" binding:"required" msg:"请完善菜单名称" structs:"title"`
	Path         string      `json:"path" binding:"required"  msg:"请完善菜单路劲" structs:"path"`
	Slogan       string      `json:"slogan" structs:"slogan"`
	Abstract     ctype.Array `json:"abstract" structs:"abstract"`
	AbstractTime int         `json:"abstract_time" structs:"abstract_time"`                // 简介切换的时间 单位秒
	ImageTime    int         `json:"image_time" structs:"image_time"`                      // 切换的事件
	Sort         int         `json:"sort" binding:"required" msg:"请完善菜单序号" structs:"sort"` // 菜单序号
	ImageIdList  []uint      `json:"image_id_list" structs:"-"`                            // 图片的序号
}

func (AdminMenuApi) MenuUpdate(c *gin.Context) {
	var req MenuUpdateReq
	if err := c.ShouldBind(&req); err != nil {
		logrus.Error(err)
		panic(err)
	}
	var menuModel models.MenuModel
	err := global.DB.Take(&menuModel, req.ID).Error
	if err != nil {
		// 查询为nil的话会出现空错误
		logrus.Error(err)
		panic(err)
	}
	err = global.DB.Transaction(func(tx *gorm.DB) error {
		// 删除两个表之间的关联表信息
		err := tx.Model(&menuModel).Association("ImageList").Clear()
		if err != nil {
			return err
		}
		// 更新菜单信息
		updateMap := structs.Map(&req)
		err = tx.Model(&menuModel).Updates(updateMap).Error
		if err != nil {
			return err
		}
		// 新增关联表信息
		if len(req.ImageIdList) > 0 {
			var menu2ImageList []models.Menu2ImageModel
			for index, imageId := range req.ImageIdList {
				menu2ImageList = append(menu2ImageList, models.Menu2ImageModel{
					MenuID:  req.ID,
					ImageID: imageId,
					Sort:    index + 1,
				})
			}
			err := tx.Create(&menu2ImageList).Error
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return
	}
	res.OkWithDate(true, c)
}
